<template>
  <div>
      <!-- 联系人 -->
      <div>
          <group class="content-other">
            <popup-radio title="联系人" :options="list" v-model="linkman" @on-show="onShow" @on-change="onChange" @on-hide="onHide">
              <p slot="popup-header" class="vux-1px-b demo3-slot">联系人</p>
            </popup-radio>
          </group>
      </div>
    
    <!-- 对话窗 -->
    <div class="msg-wrapper" ref="msgWrapper">
      <div class="msg_body">
        <ul class="newLine">
          <li v-for="(item,index) in messageInfo" :key="index" :class="item.boxType">
            <span class="msgTime">{{item.time | formatDate}}</span>
            <div><img :src="item.userImg_url" alt="" :class="item.imgType"><p :class="item.msgType">{{item.msg}}</p></div>
          </li>
        </ul>
      </div>
      <!-- <div class="msg_body">
          <ul>
              <li v-for="(item,index) in dataList.message" :key="index" :class="{
                  'time':item.type=='time',
                  'me':item.type=='message'&&item.content.from=='me',
                  'other':item.type=='message'&&item.content.from=='other'}">
                  <template v-if="item.type=='message'">
                      <img :src="item.content.faceUrl" :class="{
                       'me':item.content.from=='me',
                       'other':item.content.from=='other'}"
                       @click="$router.push(`/chat_one/${item.content.user_id}/profile`)">
                  	  <p class="message">{{item.content.message}}</p>
      				    </template>
      				    <template v-else>
      				    	{{item.content}} 
      				    </template>
              </li>
          </ul>
      </div> -->
    </div>
    <!-- 提交按钮 -->
    <div class="msg_footer">
      <textarea class="msg_input" rows="4" ref="msg"></textarea>
      <button class="msg_button" @click="addmsgInfo">发送</button>
    </div>
  </div>
</template>
<script>
import BScroll from "better-scroll"; //引入滚动插件
import { Group, PopupRadio, XButton, Toast } from "vux";
export default {
  components: {
    Group,
    PopupRadio,
    Toast
  },
  data() {
    return {
      linkman: "请选择联系人",
      list: [],
      time: Date.now(),
      messageInfo: [],
      user_id: this.$store.state.userInfo.userId,
      other_id: "",
      storageMsg:JSON.parse(localStorage.getItem("message")) || [],
      //联系人id
      users: []
    };
  },
  created() {
    //初始化获取联系人信息
    this.getOtherUser();
    //初始化获取用户id
    this.getUserId();
    //初始化本地聊天记录
    if(this.storageMsg.length===0){
      var msg = { userid:this.user_id,message:[] }
      this.users.forEach(item => {
          msg.message.push({ otherids: item, message: [] });
        });
        localStorage.setItem("message", JSON.stringify(msg));
        this.storageMsg =  JSON.parse(localStorage.getItem("message")) || [];
    }
  },
  mounted() {
    //初始化滚动插件
    setTimeout(() => {
      this._initScroll();
    }, 20);
    //页面初始化获取本地消息
  },
  methods: {
    //选择联系人
    choice() {
      console.log(this.linkman, 123);
    },
    onChange(val) {
      //监听联系人的切换
      this.other_id = val;
    },
    onShow() {
    },
    async onHide() {
      const otherid = this.other_id;

      //获取对应id的本地聊天记录
      await this.getLocalStorageMsg(otherid);
    },
    //聊天功能

    //登陆时获取该用户id，由路由传输
    getUserId() {
      // console.log(this.$route)
      //获取该用户id
      // this.user_id=this.$route.params.id
    },
    //点击联系人，获取联系人列表
    getOtherUser() {
      const linkmanInfo = [
        { key: 1, value: "张三" },
        { key: 2, value: "李四" },
        { key: 3, value: "王五" },
        { key: 4, value: "赵六" },
        { key: 5, value: "钩子七" },
        { key: 6, value: "张三1" },
        { key: 7, value: "李四2" },
        { key: 8, value: "王五3" },
        { key: 9, value: "赵六4" },
        { key: 10, value: "钩子七5" },
        { key: 11, value: "张三7" },
        { key: 12, value: "李四7" },
        { key: 13, value: "王五7" },
        { key: 14, value: "赵六7" },
        { key: 15, value: "钩子七7" },
        { key: 16, value: "张三17" },
        { key: 17, value: "李四27" },
        { key: 18, value: "王五37" },
        { key: 19, value: "赵六47" },
        { key: 20, value: "钩子七57" }
      ];
      this.list = linkmanInfo;
      //获取联系人id
      this.list.forEach(item => {
        this.users.push(item.key);
      });
    },
    //点击联系人根据联系人id获取本地存储记录
    async getLocalStorageMsg(otherid) {
      this.messageInfo = [];
      await this.storageMsg.message.some(item => {
        if (item.otherids == otherid) {
          console.log(item.otherids);
          this.messageInfo = item.message;
          console.log(this.messageInfo);
          return;
        }
      });
      //消息记录跳转到底部
      this.scrollLine();
    },
    //点击发送根据id传输数据到服务器，服务器自动推送给联系人，联系人获取服务器发送的消息添加到消息列表
    //把所有消息存储到本地
    async addmsgInfo() {
      //设置发送消息不能为空
      const msg = this.$refs.msg.value;
      console.log(this.storageMsg)
      if (msg == "") {
        this.$vux.toast.show({
          text: "请输入内容！"
        });
        return;
      } else {
        const id = this.messageInfo.length + 1;
        var newlist = [];
        this.$refs.msg.value = "";
        await this.storageMsg.message.some(item => {
          if (this.other_id == item.otherids) {
            this.messageInfo.push({
              id,
              msg,
              time: Date.now(),
              msgType: "msg_b",
              boxType: "me",
              user_id: this.user_id,
              other_id: this.other_id,
              userImg_url:require('../../assets/images/0.jpg')
            });
            item.message = this.messageInfo;
            localStorage.setItem("message", JSON.stringify(this.storageMsg));
            return;
          }
        });
        //发送内容后最滚到到最新消息位置
        setTimeout(() => {
          this.scrollLine();
        }, 20);
      }
    },
    //滚动配置
    //滚动到制定位置
    scrollLine() {
      this.$nextTick(() => {
        let msgList = this.$refs.msgWrapper.getElementsByClassName("newLine");
        if (msgList[0].children.length > 0) {
          let el = msgList[0].lastElementChild;
          console.log(msgList[0].children.length);

          this.msgScroll.scrollToElement(el, 100);
        }
      });
    },
    //初始化滚动插件
    _initScroll() {
      this.msgScroll = new BScroll(this.$refs.msgWrapper, {
        click: true,
        probeType: 3
      });
    }
  }
};
</script>
<style lang="less" scoped>
.demo3-slot {
  text-align: center;
  padding: 8px 0;
  color: #888;
}
[data-v-87212900] /deep/ .weui-cells {
  font-size: 14px;
  margin-top: 0;
}
.content {
  display: flex;
  flex-direction: column;
}
.msg-wrapper {
  /* position: fixed; */
  flex: 1;
  bottom: -5px;
  width: 100%;
  height: 300px;
  overflow: hidden;
  background: white;
  border-radius: 5px 5px 0px 0px;
}

.msgTime {
  display: inline-block;
  width: 100%;
  text-align: center;
}

.msg_head {
  background: #dddddd;
  height: 50px;
}

.msg_body {
  background: white;
  font-size: 12px;
  padding: 15px;
}

.msg_footer {
  flex: 0 0 60px;
  overflow: hidden;
}
.msg_footer /deep/ [data-v-87212900] {
  line-height: 100%;
}

.msg_input {
  display: inline-block;
  width: 80%;
  float: left;
  border: 1px solid white;
  border-top: 1px solid #dddddd;
  -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
  -moz-box-sizing: border-box; /* Firefox, other Gecko */
  box-sizing: border-box;
}

.msg_button {
  display: inline-block;
  float: left;
  width: 20%;
  height: 60px;
}
.msg_a {
  position: relative;
  background: #fde4ce;
  padding: 10px;
  min-height: 10px;
  margin-bottom: 5px;
  margin-right: 10px;
  border-radius: 5px;
  word-break: break-all;
  display: inline-block;
}
.msg_a:before {
  content: "";
  position: absolute;
  width: 0px;
  height: 0px;
  border: 10px solid;
  border-color: transparent #fde4ce transparent transparent;
  left: -20px;
  top: 7px;
}

.msg_b {
  background: #eef2e7;
  padding: 10px;
  min-height: 15px;
  margin-bottom: 5px;
  position: relative;
  margin-left: 10px;
  border-radius: 5px;
  word-wrap: break-word;
  word-break: break-all;
  display: inline-block;
  float: right;
}
.msg_b:after {
  content: "";
  position: absolute;
  width: 0px;
  height: 0px;
  border: 10px solid;
  border-color: transparent transparent transparent #eef2e7;
  right: -20px;
  top: 7px;
}
.msg_body {
  cursor: pointer;
  ul {
    width: 100%;
    li {
      padding: 6px 10px;
      img {
        border-radius: 50%;
        width: 46px;
        height: 46px;
        float: left;
      }

      p.message {
        min-height: 40px;
        line-height: 30px;
        max-width: 56%;
        display: inline-block;
        border-radius: 10px;
        padding: 6px 10px;
        word-break: break-all;
      }
    }
    div {
      margin-top: 10px;
      overflow: hidden;
      width: 100%;
    }
    li.time {
      height: 50px;
      line-height: 50px;
      font-size: 14px;
      color: #666;
      text-align: center;
    }
    li.me {
      overflow: hidden;
      img {
        float: right;
        margin-left: 20px;
      }
      p.message {
        margin-right: 10px;
        background: #1e90ff;
        color: #fff;
        float: right;
      }
    }
    li.other {
      overflow: hidden;
      img {
        float: left;
        margin-right: 20px;
      }
      p.message {
        margin-left: 10px;
        background: #fff;
        color: #000;
        float: left;
      }
    }
  }
}

</style>


